package com.cn.sys.main.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.sys.common.Constants;
import com.cn.sys.frame.util.page.PageData;
import com.cn.sys.frame.util.query.QueryBean;
import com.cn.sys.frame.util.query.QueryCondition;
import com.cn.sys.frame.web.BaseController;
import com.cn.sys.main.entity.SysRole;
import com.cn.sys.main.entity.SysUser;
import com.cn.sys.main.service.SysOrganService;
import com.cn.sys.main.service.SysRoleService;
import com.cn.sys.main.service.SysUserService;

@Controller
@RequestMapping("sys/user")
public class SysUserController extends BaseController {

	//private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);
	
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysOrganService sysOrganService;
	@RequestMapping(value = "/toList.do", method = RequestMethod.GET)
	public String toList(HttpServletRequest request, Model model){
		return "sys/user/userList";
	}
	
	@RequestMapping(value = "/list.do", method = RequestMethod.POST)
	@ResponseBody
	public Object list(HttpServletRequest request, String userName) throws Exception{
		QueryCondition queryCondition = new QueryCondition();
		if(StringUtils.isNotBlank(userName)){
			QueryBean qb = new QueryBean(" AND T1.USER_NAME LIKE ?", "T1.USER_NAME", "%"+userName+"%");
			queryCondition.setQueryBean(qb);
		}
		SysUser currentUser = getSessionUser(request);
		if(currentUser == null || !Constants.SYS_DEFAULT_USER.equals(currentUser.getUserName())){
			QueryBean qb = new QueryBean(" AND T1.USER_NAME <> ?", "T1.USER_NAME", Constants.SYS_DEFAULT_USER);
			queryCondition.setQueryBean(qb);
		}
		queryCondition.setOrderSql(" ORDER BY T1.CREATE_TIME DESC");
		PageData<SysUser> pageData = createPageDataFromRequest(request);
		sysUserService.getPageData(pageData, queryCondition);
		//sysUserService.getPageMapData(pageData, queryCondition);
		return pageData.getPageDataMap();
	}
	
	@RequestMapping(value = "/toChangePwd.do", method = RequestMethod.GET)
	public String toChangePwd(HttpServletRequest request, Model model){
		SysUser user = getSessionUser(request);
		if(user==null || user.getId()==null){
			return "../../errorPages/sessionOut";
		}
		user.setPassWord("");
		model.addAttribute("user", user);
		return "sys/user/changePwd";
	}
	
	@RequestMapping(value = "/changePwd.do", method = RequestMethod.POST)
	@ResponseBody
	public Object changePwd(SysUser user, String oldPassWord, String repeatPassWord) throws Exception{
		SysUser oldUser = sysUserService.get(user.getId());
		Map<String, Object> result = new HashMap<String, Object>(2);
		if(oldUser!=null){
			oldPassWord = DigestUtils.md5DigestAsHex(oldPassWord.getBytes()).toUpperCase();
			if(oldPassWord.equals(oldUser.getPassWord())){
				if(repeatPassWord.equals(user.getPassWord())){
					oldUser.setPassWord(DigestUtils.md5DigestAsHex(repeatPassWord.getBytes()).toUpperCase());
					sysUserService.changeUserPwd(oldUser);
					result.put("success", true);
				}else {
					result.put("success", false);
					result.put("msg", "两次输入的密码不一致!");
				}
			}else {
				result.put("success", false);
				result.put("msg", "旧密码不正确!");
			}
		}else {
			result.put("success", false);
			result.put("msg", "用户不存在!");
		}
		return result;
	}
	
	@RequestMapping(value = "/toAdd.do", method = RequestMethod.GET)
	public String toAdd(String id, Model model) throws Exception{
		if(StringUtils.isNotBlank(id) && StringUtils.isNumeric(id)){
			SysUser user = sysUserService.get(Long.valueOf(id));
			model.addAttribute("user", user);
		}
		return "sys/user/userAdd";
	}
	
	@RequestMapping(value = "/toView.do", method = RequestMethod.GET)
	public String toView(String id, Model model) throws Exception{
		if(StringUtils.isNotBlank(id) && StringUtils.isNumeric(id)){
			SysUser user = sysUserService.get(Long.valueOf(id));
			model.addAttribute("user", user);
			List<SysRole> roleList = sysRoleService.getRoleListByUserId(id);
			model.addAttribute("roleList", roleList);
			if(user.getOrganId()!=null){
				model.addAttribute("organName", sysOrganService.get(user.getOrganId()).getName());
			}
		}
		return "sys/user/userView";
	}
	
	@RequestMapping(value = "/validateUserName.do", method = RequestMethod.POST)
	@ResponseBody
	public Object validateUserName(String id, String name) throws Exception{
		QueryCondition queryCondition = new QueryCondition();
		if(StringUtils.isNotBlank(id)){
			QueryBean qb = new QueryBean(" AND ID <> ?", "ID", Long.valueOf(id));
			queryCondition.setQueryBean(qb);
		}
		if(StringUtils.isNotBlank(name)){
			queryCondition.setQueryBean(new QueryBean(" AND USER_NAME = ?", "USER_NAME", name));
		}else {
			return false;
		}
		long count = sysUserService.getCount(queryCondition);
		if(count>0){
			return false;
		}
		return true;
	}
	
	@RequestMapping(value = "/save.do", method = RequestMethod.POST)
	@ResponseBody
	public Object save(HttpServletRequest request, SysUser user) throws Exception{
		if(user !=null && user.getId() !=null){
			SysUser oldUser = sysUserService.get(user.getId());
			if(!StringUtils.equals(user.getStatus(), "1")){
				user.setStatus("0");
			}
			user.setPassWord(oldUser.getPassWord());
			user.setCreateTime(oldUser.getCreateTime());
			user.setCreateUser(oldUser.getCreateUser());
			user.setUpdateTime(new Date());
			user = sysUserService.update(user);
		}else {
			if(!StringUtils.equals(user.getStatus(), "1")){
				user.setStatus("0");
			}
			user.setPassWord(DigestUtils.md5DigestAsHex(Constants.USER_INIT_PWD.getBytes()).toUpperCase());
			user.setCreateTime(new Date());
			SysUser currentUser = getSessionUser(request);
			user.setCreateUser(currentUser!=null?currentUser.getUserName():null);
			user = sysUserService.save(user);
		}
		Map<String, Object> result = new HashMap<String, Object>(1);
		if(user==null){
			result.put("success", false);
		}else {
			result.put("success", true);
		}
		return result;
	}
	
	@RequestMapping(value = "/delete.do", method = RequestMethod.POST)
	@ResponseBody
	public Object delete(HttpServletRequest request, String ids) throws Exception{
		Map<String, Object> result = new HashMap<String, Object>(2);
		if(ids!=null){
			int count = 0;
			String[] strArr = ids.split(",");
				for (int i=0,len=strArr.length; i<len; i++) {
					String id = strArr[i];
					if(StringUtils.isNotBlank(id)&&StringUtils.isNumeric(id)){
						int resultCnt = sysUserService.delete(Long.valueOf(id));
						if(resultCnt == 1){
							count ++;
						}
					}
				}
			if(count == strArr.length){
				result.put("success", true);
			} else {
				result.put("success", false);
				result.put("msg", (strArr.length - count)+"条记录删除失败!");
			}
			
		}else {
			result.put("success", false);
		}
		return result;
	}
	
	@RequestMapping(value = "/toAssignRoles.do", method = RequestMethod.GET)
	public String toAssignRoles(String id, Model model) throws Exception{
		//List<SysRole> list = sysRoleService.getAll();
		List<Map<String, Object>> list = sysRoleService.getRolesByUserId(id);
		model.addAttribute("userId", id);
		model.addAttribute("userRoles", list);
		return "sys/user/userAssignRoles";
	}
	
	@RequestMapping(value = "/saveUserRoles.do", method = RequestMethod.POST)
	@ResponseBody
	public Object saveUserRoles(String userId, String roleIds) throws Exception{
		Map<String, Object> result = new HashMap<String, Object>(1);
		if(StringUtils.isNotBlank(userId)){
			boolean rel = sysUserService.assignRoleSave(userId, roleIds);
			if(rel){
				result.put("success", true);
			}else {
				result.put("success", false);
				result.put("msg", "分配角色失败");
			}
		}else {
			result.put("success", false);
		}
		return result;
	}
	
	@RequestMapping(value = "/initUserPwd.do", method = RequestMethod.POST)
	@ResponseBody
	public Object initUserPwd(HttpServletRequest request, String ids) throws Exception{
		Map<String, Object> result = new HashMap<String, Object>(2);
		if(ids!=null){
			int count = ids.split(",").length;
			int count2 = sysUserService.initUserPwd(ids);
			if(count==1&&count==count2){
				result.put("success", true);
			}else if(count==1&&count!=count2){
				result.put("success", false);
			}else if(count==count2){
				result.put("success", true);
			}else {
				result.put("success", false);
				result.put("msg", (count - count2)+"条记录初始化密码失败!");
			}
		}else {
			result.put("success", false);
		}
		return result;
	}
}
